package com.klod

import com.klod.data.bean.BaseResponseBean
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.util.cio.*
import io.ktor.utils.io.*
import java.io.File
import java.util.*

/**
 * 这里配置一些公共的路由
 */
fun Application.configureRouting() {
    routing {


        post("/upload") {
            val multipart = call.receiveMultipart()
            var fileUrl: String? = null

            multipart.forEachPart { part ->
                when (part) {
                    is PartData.FileItem -> {


                        // 生成唯一文件名
                        val fileName = UUID.randomUUID().toString() + "_" + part.originalFileName
                        // 文件保存路径（示例路径：项目根目录下的uploads文件夹）
                        val uploadDir = File("images/uploads")
                        if (!uploadDir.exists()) uploadDir.mkdirs()
                        val file = File(uploadDir, fileName)


                        part.provider().copyAndClose(file.writeChannel())

                        // 构建可访问的URL
                        fileUrl =
                            "${
                                call.request.local.scheme
                            }://${
                                call.request.host()
                            }:${
                                call.request.port()
                            }/files/$fileName"
                    }

                    is PartData.FormItem -> {
                        println(part.name + " = " + part.value)
                    }
                    else -> {

                    }

                }
                part.dispose()
            }

            fileUrl?.let { url ->
                call.respond(BaseResponseBean.success(mapOf("url" to url)))
            } ?: call.respond(HttpStatusCode.BadRequest, "No file uploaded")
        }

    }
}
